import locale
from pathlib import Path


def sort_text_lines(file_p, output_path):
    try:
        with open(file_p, 'r', encoding='utf-8') as file:
            lines = [line.strip() for line in file]
        sorted_lines = sorted(lines, key=locale.strxfrm)

        if output_path.exists():
            backup_name = output_path.with_suffix(output_path.suffix + '.bak')
            output_path.rename(backup_name)

        with open(output_path, 'w', encoding='utf-8') as new_file:
            for line in sorted_lines:
                new_file.write(line + '\n')

    except FileNotFoundError:
        print(f"文件 {file_p} 未找到。")
    except Exception as e:
        print(f"处理文件时发生错误：{e}")


locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
txt = Path(r'1.txt')
new_name = txt.stem + '_sort' + txt.suffix
new_path = txt.parent / new_name
sort_text_lines(txt, new_path)
